﻿using System;
using System.Globalization;
using System.IO;
using QuanLyHopDong.Biz;
using QuanLyHopDong.Biz.Model;
using Resources;

namespace QuanLyHopDong.Web.HopDong
{
    public partial class PhieuXuatKhoEdit : System.Web.UI.Page
    {
        #region Properties

        private PhieuXuatKhoBiz _phieuXuatKhoBiz;

        private PhieuXuatKhoBiz PhieuXuatKhoManager
        {
            get { return _phieuXuatKhoBiz ?? (_phieuXuatKhoBiz = new PhieuXuatKhoBiz()); }
        }

        private HopDongBiz _hopDongBiz;
        private HopDongBiz HopDongManager
        {
            get { return _hopDongBiz ?? (_hopDongBiz = new HopDongBiz()); }
        }

        private int _hopDongId;
        private int HopDongId
        {
            get
            {
                if (_hopDongId <= 0)
                    int.TryParse(Request.QueryString["hopDongId"], out _hopDongId);
                return _hopDongId;
            }
        }

        private HopDongView _hopDongView;
        private HopDongView CurrentHopDongView
        {
            get
            {
                if (_hopDongView == null && HopDongId > 0)
                {
                    _hopDongView = HopDongManager.GetById(HopDongId);
                }
                return _hopDongView;
            }
        }

        private int _phieuXuatKhoId;
        private int PhieuXuatKhoId
        {
            get
            {
                if (_phieuXuatKhoId <= 0)
                    int.TryParse(Request.QueryString["id"], out _phieuXuatKhoId);
                return _phieuXuatKhoId;
            }
        }

        private PhieuXuatKho _phieuXuatKho;

        private PhieuXuatKho CurrentPhieuXuatKho
        {
            get
            {
                if (_phieuXuatKho == null && PhieuXuatKhoId > 0)
                {
                    _phieuXuatKho = PhieuXuatKhoManager.GetById(PhieuXuatKhoId);
                }
                return _phieuXuatKho;
            }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (CurrentHopDongView == null)
                {
                    lblErrorMessage.Text = string.Format("{0}: Id={1}", GlobalStrings.NotExisted, HopDongId);
                    btnSave.Visible = false;
                    return;
                }

                LoadHopDongData();
                LoadPhieuXuatKhoData();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblErrorMessage.Text = string.Empty;

            #region collect inputs and validate

            var phieuXuatKho = new PhieuXuatKho
            {
                Id=PhieuXuatKhoId,
                HopDongId = HopDongId,
                SoPhieu = txtSoPhieu.Text.Trim(),
                GhiChu = txtGhiChu.Text
            };

            DateTime ngayChungTu;
            if (DateTime.TryParseExact(txtNgayChungTu.Text.Trim(), GlobalStrings.DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ngayChungTu))
            {
                phieuXuatKho.NgayChungTu = ngayChungTu;
            }

            var filePhieuXuatName = string.Empty;
            if (filePhieuXuatKho.HasFile)
            {
                filePhieuXuatName = Path.GetFileName(filePhieuXuatKho.PostedFile.FileName);
                phieuXuatKho.PhieuXuatKho1 = filePhieuXuatName;
            }
            else
            {
                phieuXuatKho.PhieuXuatKho1 = CurrentPhieuXuatKho.PhieuXuatKho1;
            }

            var fileBienBanName = string.Empty;
            if (fileBienBanBanGiao.HasFile)
            {
                fileBienBanName = Path.GetFileName(fileBienBanBanGiao.PostedFile.FileName);
                phieuXuatKho.BienBanBanGiao = fileBienBanName;
            }
            else
            {
                phieuXuatKho.BienBanBanGiao = CurrentPhieuXuatKho.BienBanBanGiao;
            }

            // delete old file
            if (filePhieuXuatKho.HasFile)
            {
                if (!string.IsNullOrEmpty(CurrentPhieuXuatKho.PhieuXuatKho1))
                {
                    var filePath =
                        Server.MapPath(string.Format("~/Files/HopDong/{0}/{1}", HopDongId,
                            CurrentPhieuXuatKho.PhieuXuatKho1));
                    PhieuXuatKhoManager.DeleteFilePhieuXuatKho(filePath, CurrentPhieuXuatKho.Id);
                }
            }
            if (fileBienBanBanGiao.HasFile)
            {
                if (!string.IsNullOrEmpty(CurrentPhieuXuatKho.BienBanBanGiao))
                {
                    var filePath =
                        Server.MapPath(string.Format("~/Files/HopDong/{0}/{1}", HopDongId,
                            CurrentPhieuXuatKho.BienBanBanGiao));
                    PhieuXuatKhoManager.DeleteFileBienBanBanGiao(filePath, CurrentPhieuXuatKho.Id);
                }
            }

            // update PhieuXuatKho
            try
            {
                PhieuXuatKhoManager.Update(phieuXuatKho);
            }
            catch (Exception ex)
            {
                lblErrorMessage.Text = ex.Message;
                return;
            }

            // upload files
            if (filePhieuXuatKho.HasFile)
            {
                // create folder
                var folderPath = Server.MapPath(string.Format("~/Files/HopDong/{0}", HopDongId));
                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);

                // save new file
                var filePathFull = folderPath + "/" + filePhieuXuatName;
                if (File.Exists(filePathFull))
                    File.Delete(filePathFull);
                filePhieuXuatKho.PostedFile.SaveAs(filePathFull);

                lnkFilePhieuXuat.Text = filePhieuXuatName;
                lnkFilePhieuXuat.NavigateUrl = string.Format("~/Files/HopDong/{0}/{1}", HopDongId, filePhieuXuatName);
                lnkDeleteFilePhieuXuat.Visible = true;
            }
            if (fileBienBanBanGiao.HasFile)
            {
                // create folder
                var folderPath = Server.MapPath(string.Format("~/Files/HopDong/{0}", HopDongId));
                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);

                // save new file
                var filePathFull = folderPath + "/" + fileBienBanName;
                if (File.Exists(filePathFull))
                    File.Delete(filePathFull);
                fileBienBanBanGiao.PostedFile.SaveAs(filePathFull);

                lnkBienBanBanGiao.Text = fileBienBanName;
                lnkBienBanBanGiao.NavigateUrl = string.Format("~/Files/HopDong/{0}/{1}", HopDongId, fileBienBanName);
                lnkDeleteFileBienBanBanGiao.Visible = true;
            }

            lblErrorMessage.Text = GlobalStrings.UpdateSuccess;

            #endregion
        }

        protected void lnkDeleteFilePhieuXuat_Click(object sender, EventArgs e)
        {
            try
            {
                var filePath =
                    Server.MapPath(string.Format("~/Files/HopDong/{0}/{1}", HopDongId,
                        CurrentPhieuXuatKho.PhieuXuatKho1));

                PhieuXuatKhoManager.DeleteFilePhieuXuatKho(filePath, CurrentPhieuXuatKho.Id);
                lnkFilePhieuXuat.Text = string.Empty;
                lnkFilePhieuXuat.NavigateUrl = string.Empty;

                lblErrorMessage.Text = string.Empty;
                lnkDeleteFilePhieuXuat.Visible = false;
            }
            catch (Exception ex)
            {
                lblErrorMessage.Text = ex.Message;
            }
        }

        protected void lnkDeleteFileBienBanBanGiao_Click(object sender, EventArgs e)
        {
            try
            {
                var filePath =
                    Server.MapPath(string.Format("~/Files/HopDong/{0}/{1}", HopDongId,
                        CurrentPhieuXuatKho.BienBanBanGiao));

                PhieuXuatKhoManager.DeleteFileBienBanBanGiao(filePath, CurrentPhieuXuatKho.Id);
                lnkBienBanBanGiao.Text = string.Empty;
                lnkBienBanBanGiao.NavigateUrl = string.Empty;

                lblErrorMessage.Text = string.Empty;
                lnkDeleteFileBienBanBanGiao.Visible = false;
            }
            catch (Exception ex)
            {
                lblErrorMessage.Text = ex.Message;
            }
        }

        #endregion

        #region Helpers

        public void LoadHopDongData()
        {
            ltrTenDonVi.Text = CurrentHopDongView.TenDonVi;
            ltrSoHopDong.Text = CurrentHopDongView.SoHopDong;
            ltrLoaiDuAn.Text = CurrentHopDongView.LoaiDuAn;
        }

        public void LoadPhieuXuatKhoData()
        {
            txtSoPhieu.Text = CurrentPhieuXuatKho.SoPhieu;
            txtNgayChungTu.Text = string.Format("{0:dd/MM/yyyy}", CurrentPhieuXuatKho.NgayChungTu);
            txtGhiChu.Text = CurrentPhieuXuatKho.GhiChu;
            if (!string.IsNullOrEmpty(CurrentPhieuXuatKho.PhieuXuatKho1))
            {
                lnkFilePhieuXuat.Text = CurrentPhieuXuatKho.PhieuXuatKho1;
                lnkFilePhieuXuat.NavigateUrl = string.Format("~/Files/HopDong/{0}/{1}", HopDongId, CurrentPhieuXuatKho.PhieuXuatKho1);
                lnkDeleteFilePhieuXuat.Visible = true;
            }
            else
            {
                lnkDeleteFilePhieuXuat.Visible = false;
            }
            if (!string.IsNullOrEmpty(CurrentPhieuXuatKho.BienBanBanGiao))
            {
                lnkBienBanBanGiao.Text = CurrentPhieuXuatKho.BienBanBanGiao;
                lnkBienBanBanGiao.NavigateUrl = string.Format("~/Files/HopDong/{0}/{1}", HopDongId, CurrentPhieuXuatKho.BienBanBanGiao);
                lnkDeleteFileBienBanBanGiao.Visible = true;
            }
            else
            {
                lnkDeleteFileBienBanBanGiao.Visible = false;
            }
        }

        #endregion
    }
}